<?php
namespace app\api\controller;

use app\admin\library\ImSig;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Date;
use fast\Random;
use think\Config;
use think\Db;
use think\Loader;
use think\Page;
use think\Validate;
use \app\admin\model\Activity as Activitys;
use \app\admin\model\Signin;
use \app\admin\model\VisitingMaterials;
use \app\admin\model\Volunteer;
use \app\admin\model\VolunteerAudit;
use \app\api\model\Recharge;
use \app\manystore\model\Goods as GoodsModel;

/**
 * 用戶接口
 */
class User extends Api
{
    protected $noNeedLogin = ['getSosList'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @MethodName 獲取用戶資料
     * @Author     Allen
     * @DateTime   2021-10-05T15:03:47+0800
     * @return     [type]
     */
    public function index()
    {
        $vmodel    = new Volunteer;
        $smodel    = new Signin;
        $vamodel   = new VolunteerAudit;
        $user_info = $this->auth->getUserinfo();

        $user = ['id' => $user_info['id'], 'avatar' => $user_info['avatar'], 'nickname' => $user_info['nickname'], 'user_type' => 1, 'level' => $user_info['level_name'], 'region' => '', 'score' => $user_info['score'], 'collection_num' => 0, 'workinghours' => $user_info['workinghours'], 'interface_style' => $user_info['interface_style'], 'province' => $user_info['province'], 'city' => $user_info['city'], 'district' => $user_info['district'], 'area_one_id' => 0, 'area_tow_id' => 0, 'countryCode' => $user_info['countryCode'], 'mobile' => $user_info['mobile']];

        if (! $user['level']) {
            $user['level'] = db('volunteer_level')
                ->order('id asc')
                ->value('name');
        }
        $user['collection_num'] = db('collection')
            ->where(['user_id' => $this->auth->id, 'type' => ['neq', 6]])
            ->count();

        $where       = ['c.user_id' => $this->auth->id, 'c.type' => '6', 'g.goods_status' => '10'];
        $model       = new GoodsModel;
        $goods_total = $model
            ->alias('g')
            ->where($where)
            ->join('collection c', 'c.relation_id = g.goods_id')
            ->count();

        $user['collection_num'] += $goods_total;

        $volunteer = $vmodel
            ->where(['user_id' => $this->auth->id])
            ->find();

        // 義工審核狀態0、未成為義工,1待審核2通過3拒絕
        $volunteer_audit_status = 0;

        $volunteer_audit = $vamodel
            ->where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->find();

        if ($volunteer_audit) {
            $volunteer_audit_status = $volunteer_audit['status'];
        }

        // 審核通過，但是把義工身份刪除了
        if (isset($volunteer_audit) && $volunteer_audit['status'] == 2 && ! $volunteer) {
            $volunteer_audit_status = 0;
        }

        if ($volunteer) {
            $volunteer_audit_status = 2;
            $user['user_type']      = 2;

            $region_address = db('area')
                ->where(['id' => $volunteer['area_one_id']])
                ->value('name');

            $city = db('area')
                ->where(['id' => $volunteer['area_tow_id']])
                ->value('name');

            if ($city) {
                $region_address = $region_address . $city;
            }
            $user['region']      = $region_address ? $region_address : '';
            $user['area_one_id'] = $volunteer['area_one_id'];
            $user['area_tow_id'] = $volunteer['area_tow_id'];

        }

        $user['volunteer_audit_status'] = $volunteer_audit_status;

        $user['signin_status'] = $smodel
            ->where('user_id', $this->auth->id)
            ->whereTime('createtime', 'today')
            ->count();

        //资料
        $visiting_materials_model = new VisitingMaterials;

        $info = $visiting_materials_model->where(['user_id' => $this->auth->id])->find();

        $volunteers     = Db::name('volunteer')->where('user_id', $this->auth->id)->where('deletetime',null)->select();
        $ids            = array_column($volunteers, 'affiliated_center_id');
        $area           = Db::name('area')->where('id', 'in', $ids)->select();
        $ids2           = array_column($area, 'name');
        $user['region'] = implode($ids2, ';');

        $this->success('請求成功', $user);
    }

    /**
     * @MethodName 義工等級經驗列表
     * @Author     Allen
     * @DateTime   2021-10-09T15:45:43+0800
     * @param      string
     * @return     [type]
     */
    public function expList($value = '')
    {
        $where = ['user_id' => $this->auth->id, 'exp' => ['gt', 0]];
        $total = db('task_log')
            ->where($where)
            ->count();

        $page = new Page($total, 10);
        $list = db('task_log')
            ->field('relation_id,type,exp,createtime')
            ->where($where)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('createtime desc')
            ->select();

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];

        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 獲得工時列表
     * @Author     Allen
     * @DateTime   2021-10-09T15:45:43+0800
     * @param      string
     * @return     [type]
     */
    public function workinghoursList($value = '')
    {
        $where = ['a.user_id' => $this->auth->id];
        $total = db('activity_sign')->alias('a')
            ->where($where)
            ->count();

        $page = new Page($total, 10);
        $list = db('activity_sign')->alias('a')
            ->join('activity ac', 'ac.id=a.activity_id')
            ->field('a.*,ac.images')
            ->where($where)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('a.createtime desc')
            ->select();
        $totalHours = db('activity_sign')->alias('a')
            ->where($where)
            ->sum('hours');
        $data = ['totalHours' => $totalHours, 'total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];

        $this->success('請求成功', $data);
    }

/**
 * @MethodName 獲取收藏的文章（大灣區資訊、大灣區調查、工聯中心、互助廣場）
 * @Author     Allen
 * @DateTime   2021-10-09T16:59:54+0800
 * @param      string
 * @return     [type]
 */
    public function getArticlecollection($value = '')
    {
        $subQuery = "(
                SELECT
                  a.id,a.title,a.images,a.createtime, 1 AS type
                FROM
                  " . config('database.prefix') . "article as a INNER JOIN " . config('database.prefix') . "collection as c ON c.relation_id=a.id WHERE (c.user_id = " . $this->auth->id . " and c.type = 1 and a.deletetime is NULL)
                UNION
                  SELECT
                    i.id,i.title,i.images,i.createtime, 2 AS type
                  FROM
                    " . config('database.prefix') . "investigate as i INNER JOIN " . config('database.prefix') . "collection as c ON c.relation_id=i.id WHERE (c.user_id = " . $this->auth->id . " and c.type = 2 and i.deletetime is NULL)
                  UNION
                    SELECT
                      f.id,f.title,f.images,f.createtime, 3 AS type
                    FROM
                      " . config('database.prefix') . "fotu as f INNER JOIN " . config('database.prefix') . "collection as c ON c.relation_id=f.id WHERE (c.user_id = " . $this->auth->id . " and c.type = 3 and f.deletetime is NULL)
                  UNION
                    SELECT
                      j.id,j.title,j.images,j.createtime, 7 AS type
                    FROM
                      " . config('database.prefix') . "join_article as j INNER JOIN " . config('database.prefix') . "collection as c ON c.relation_id=j.id WHERE (c.user_id = " . $this->auth->id . " and c.type = 7 and j.deletetime is NULL)
                  UNION
                    SELECT
                      j.id,j.title,j.images,j.createtime, 8 AS type
                    FROM
                      " . config('database.prefix') . "join_article as j INNER JOIN " . config('database.prefix') . "collection as c ON c.relation_id=j.id WHERE (c.user_id = " . $this->auth->id . " and c.type = 8 and j.deletetime is NULL)
                      UNION
                    SELECT
                      h.id,n.name as title,h.imagess as images,h.createtime, 4 AS type
                    FROM
                      " . config('database.prefix') . "help_task as h LEFT JOIN " . config('database.prefix') . "help_name as n ON n.id=h.help_name_id INNER JOIN " . config('database.prefix') . "collection as c ON c.relation_id=h.id WHERE (c.user_id = " . $this->auth->id . " and c.type = 4 and h.deletetime is NULL)
                        )";
        $total = Db::table($subQuery . ' a')
            ->count();

        $page = new Page($total, 10);

        $list = Db::table($subQuery . ' a')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('createtime', 'desc')
            ->select();

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];

        $this->success('請求成功', $data);
    }

/**
 * @MethodName 獲取收藏的活動
 * @Author     Allen
 * @DateTime   2021-10-09T16:59:54+0800
 * @param      string
 * @return     [type]
 */
    public function getActivitycollection($value = '')
    {
        $where = ['c.user_id' => $this->auth->id, 'c.type' => '5'];
        $model = new Activitys;
        $total = $model
            ->alias('a')
            ->where($where)
            ->join('collection c', 'c.relation_id = a.id')
            ->count();

        $page = new Page($total, 10);

        $list = $model
            ->field('a.id,a.images,a.title,a.createtime,5 as type')
            ->alias('a')
            ->where($where)
            ->join('collection c', 'c.relation_id = a.id')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('weigh desc,id desc')
            ->select();

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];

        $this->success('請求成功', $data);
    }

/**
 * @MethodName 獲取收藏的商品
 * @Author     Allen
 * @DateTime   2021-10-09T16:59:54+0800
 * @param      string
 * @return     [type]
 */
    public function getGoodscollection($value = '')
    {
        $where = ['c.user_id' => $this->auth->id, 'c.type' => '6', 'g.goods_status' => '10'];
        $model = new GoodsModel;
        $total = $model
            ->alias('g')
            ->where($where)
            ->join('collection c', 'c.relation_id = g.goods_id')
            ->count();

        $page = new Page($total, 10);

        $list = $model
            ->field('g.goods_id,g.type,g.images,g.goods_name,c.createtime')
            ->alias('g')
            ->where($where)
            ->join('collection c', 'c.relation_id = g.goods_id')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('weigh desc,c.id desc')
            ->select();

        foreach ($list as $key => &$value) {
            $value['images']    = explode(',', $value['images'])[0];
            $value->line_price  = 0;
            $value->goods_price = 0;
            $value->integral    = 0;
            $min_price          = db('goods_spec')
                ->where(['goods_id' => $value->goods_id])
                ->order('goods_price asc')
                ->find();

            if ($min_price) {
                $value->goods_price = $min_price['goods_price'];
                $value->line_price  = $min_price['line_price'];
                $value->integral    = $min_price['integral'];
            }
        }
        unset($value);

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];

        $this->success('請求成功', $data);
    }

/**
 * @MethodName 獲取sos緊急呼叫列表
 * @Author     Allen
 * @DateTime   2021-10-10T01:34:54+0800
 * @param      string
 * @return     [type]
 */
    public function getSosList($value = '')
    {
        $time_type = '1';
        $new_day   = date("l");

        $new_day = strtolower($new_day);
        if ($new_day == "saturday" || $new_day == "sunday") {
            $time_type = '2';
        }

        // $sql = "SELECT
        //         id,name,area_number
        //     FROM
        //         ".config('database.prefix')."sos
        //     WHERE deletetime IS NULL AND time_type = ".$time_type."
        //     AND (
        //             (
        //                 office_hours_start <= CURTIME()
        //                 AND office_hours_end >= CURTIME()
        //             )
        //             OR (
        //                 office_hours_start = '00:00:00'
        //                 AND office_hours_end = '00:00:00'
        //             )
        //         )
        //     ORDER BY
        //         `id` DESC
        //     ";
        //  $query_list = Db::query($sql);
        // dd($query_list);

        $list = db('sos')
            ->field('id,name,area_number,time_type,office_hours_start,office_hours_end')
            ->where(['deletetime' => null])
            ->order('id desc')
            ->select();

        $time  = time();
        $today = date('Y-m-d');
        foreach ($list as $key => &$value) {
            $value['status'] = 2;
            if ($value['time_type'] == $time_type) {
                if ($value['office_hours_start'] == '00:00:00' && $value['office_hours_end'] == '00:00:00') {
                    $value['status'] = 1;
                    unset($value['time_type']);
                    unset($value['office_hours_start']);
                    unset($value['office_hours_end']);
                    continue;
                }

                $office_hours_start           = $today . " " . $value['office_hours_start'];
                $office_hours_end             = $today . " " . $value['office_hours_end'];
                $office_hours_start_strtotime = strtotime($office_hours_start);
                $office_hours_end_strtotime   = strtotime($office_hours_end);

                if ($office_hours_start_strtotime <= $time && $office_hours_end_strtotime >= $time) {
                    $value['status'] = 1;
                }
            }
            unset($value['time_type']);
            unset($value['office_hours_start']);
            unset($value['office_hours_end']);
        }
        unset($value);
        $this->success('請求成功', $list);
    }

/**
 * 立即簽到
 */
    public function dosign()
    {
        $time   = time();
        $smodel = new Signin;
        $score  = db('system_config')
            ->where(['name' => 'signin_integral', 'group' => 'system_configuration'])
            ->value('value');

        $lastdata = $smodel
            ->where('user_id', $this->auth->id)->order('createtime', 'desc')
            ->find();

        $successions = $lastdata && $lastdata['createtime'] > Date::unixtime('day', -1) ? $lastdata['successions'] : 0;

        $signin = $smodel
            ->where('user_id', $this->auth->id)
            ->whereTime('createtime', 'today')
            ->find();

        if ($signin) {
            $this->error('今天已簽到,請明天再來!');
        } else {
            $successions++;
            Db::startTrans();
            try {
                $smodel->create(['user_id' => $this->auth->id, 'successions' => $successions, 'createtime' => $time]);
                if ($score > 0) {
                    addPoints($this->auth->id, $score, '每日簽到', 3, 0, $time);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error('簽到失敗,請稍後重試');
            }
            $msg = '簽到成功!';
            if ($score > 0) {
                $msg = $msg . '獲得' . $score . '積分';
            }
            $this->success($msg);
        }
    }

/**
 * [getInformation 獲取系統資料]
 * @MethodName
 * @Author     Allen
 * @DateTime   2021-10-10T17:00:23+0800
 * @param      string                   $value [description]
 * @return     [type]                          [description]
 */
    public function getInformation($value = '')
    {
        $list = db('system_config')
            ->where(['group' => 'system_configuration', 'name' => ['in', ['home_web_url', 'home_app_url', 'integral_recharge_ratio']]])
            ->select();

        $home_web_url            = '';
        $home_app_url            = '';
        $integral_recharge_ratio = 0;
        foreach ($list as $key => $value) {
            if ($value['name'] == 'home_web_url') {
                $home_web_url = $value['value'];
            }
            if ($value['name'] == 'home_app_url') {
                $home_app_url = $value['value'];
            }
            if ($value['name'] == 'integral_recharge_ratio') {
                $integral_recharge_ratio = $value['value'];
            }
        }

        $this->success('請求成功', ['home_web_url' => $home_web_url, 'home_app_url' => $home_app_url, 'integral_recharge_ratio' => $integral_recharge_ratio]);
    }

/**
 * [setInterfaceStyle 設置界面風格]
 * @MethodName
 * @Author     Allen
 * @DateTime   2021-10-10T17:11:18+0800
 * @param      string                   $value [description]
 */
    public function setInterfaceStyle($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('InterfaceStyle');

        if (! $validate->scene('interface_style')->check($rq_data)) {
            $this->error($validate->getError());
        }

        db('user')
            ->where(['id' => $this->auth->id])
            ->update(['interface_style' => $rq_data['interface_style']]);

        $this->success('操作成功');
    }

/**
 * [doMessage 留言]
 * @MethodName
 * @Author     Allen
 * @DateTime   2021-10-10T17:19:38+0800
 * @param      string                   $value [description]
 * @return     [type]                          [description]
 */
    public function doMessage($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Message');
        if (! $validate->scene('do')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $insert                         = [];
        $insert['user_id']              = $this->auth->id;
        $insert['affiliated_center_id'] = isset($rq_data['affiliated_center_id']) ? $rq_data['affiliated_center_id'] : 0;
        $insert['name']                 = $rq_data['name'];
        $insert['mobile']               = $rq_data['mobile'];
        $insert['content']              = $rq_data['content'];
        $insert['createtime']           = time();

        $status = db('message_board')->insert($insert);

        if (! $status) {
            $this->error('操作失敗');
        }
        $this->success('操作成功');
    }

/**
 * 修改手機號
 *
 * @ApiMethod (POST)
 * @param string $mobile  手機號
 * @param string $captcha 驗證碼
 */
    public function changemobile()
    {
        $user        = $this->auth->getUser();
        $mobile      = $this->request->post('mobile');
        $countryCode = $this->request->post('countryCode');
        $captcha     = $this->request->post('captcha');
        if (! $mobile || ! $captcha) {
            $this->error('參數錯誤');
        }
        // if (!Validate::regex($mobile, "^1\d{10}$")) {
        //     $this->error(__('Mobile is incorrect'));
        // }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error('手機號碼已被佔用');
        }

        // $result = true;
        // if ( $captcha != '1234' ) {
        //   $result = false;
        // }

        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (! $result) {
            $this->error('驗證碼不正確');
        }
        $verification         = $user->verification;
        $verification->mobile = 1;
        $user->verification   = $verification;
        $user->mobile         = $mobile;
        $user->countryCode    = $countryCode;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success('操作成功');
    }

/**
 * [verificationmobile 驗證原手機]
 * @MethodName
 * @Author     Allen
 * @DateTime   2021-11-03T14:49:49+0800
 * @param      string                   $value [description]
 * @return     [type]                          [description]
 */
    public function verificationmobile($value = '')
    {
        $mobile  = $this->auth->mobile;
        $captcha = $this->request->post('captcha');
        if (! $captcha) {
            $this->error('參數錯誤');
        }

        // $result = true;
        // if ($captcha != '1234') {
        //     $result = false;
        // }

        $result = Sms::check($mobile, $captcha, 'verificationmobile');

        if (! $result) {
            $this->error('驗證碼不正確');
        }

        Sms::flush($mobile, 'verificationmobile');
        $this->success('驗證成功');
    }

/**
 * 修改用戶個人信息
 *
 * @ApiMethod (POST)
 */
    public function profile()
    {
        $user = $this->auth->getUser();
        // 頭像
        $avatar = $this->request->post('avatar');
        // 暱稱
        $nickname = $this->request->post('nickname');
        // 省
        $province = $this->request->post('province');
        // 市
        $city = $this->request->post('city');
        // 區
        $district = $this->request->post('district');
        // 一級區域ID
        $area_one_id = $this->request->post('area_one_id');
        // 二級區域ID
        $area_tow_id = $this->request->post('area_tow_id');

        if (isset($avatar)) {
            $user->avatar = $avatar;
        }
        if (isset($nickname)) {
            $user->nickname = $nickname;
        }
        if (isset($province)) {
            $user->province = $province;
        }
        if (isset($city)) {
            $user->city = $city;
        }
        if (isset($district)) {
            $user->district = $district;
        }

        $volunteer_arr = [];
        if (isset($area_one_id)) {
            $volunteer_arr['area_one_id'] = $area_one_id;
        }
        if (isset($area_tow_id)) {
            $volunteer_arr['area_tow_id'] = $area_tow_id;
        }

        $user->save();

        $volunteer_info = db('volunteer')
            ->where(['user_id' => $this->auth->id, 'deletetime' => null])
            ->find();

        if ($volunteer_arr && $volunteer_info) {
            $volunteer_arr['updatetime'] = time();
            db('volunteer')
                ->where(['id' => $volunteer_info['id']])
                ->update($volunteer_arr);
        }
        $this->success('操作成功');
    }

/**
 * [rechargeIntegral 積分充值]
 * @MethodName
 * @Author     Allen
 * @DateTime   2021-10-16T16:18:56+0800
 * @param      string                   $value [description]
 * @return     [type]                          [description]
 */
    public function rechargeIntegral($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Recharge');
        if (! $validate->scene('recharge_integral')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $integral_recharge_ratio = db('system_config')
            ->where(['group' => 'system_configuration', 'name' => 'integral_recharge_ratio'])
            ->value('value');
        if (! $integral_recharge_ratio) {
            $this->error('抱歉，當前並未開啟積分充值功能');
        }

        $integral                              = $integral_recharge_ratio * $rq_data['payment_amount'];
        $insert_arr                            = [];
        $insert_arr['order_no']                = orderNo(4);
        $insert_arr['user_id']                 = $this->auth->id;
        $insert_arr['payment_amount']          = $rq_data['payment_amount'];
        $insert_arr['integral']                = $integral;
        $insert_arr['integral_recharge_ratio'] = $integral_recharge_ratio;
        $insert_arr['ip']                      = request()->ip();
        $insert_arr['createtime']              = time();

        $model  = new Recharge;
        $status = $model->insertGetId($insert_arr);
        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功', ['id' => $status, 'order_no' => $insert_arr['order_no']]);
    }

/**
 * [getScoreLog 獲取積分記錄]
 * @MethodName
 * @Author     Allen
 * @DateTime   2021-10-17T16:09:32+0800
 * @param      string                   $value [description]
 * @return     [type]                          [description]
 */
    public function getScoreLog($value = '')
    {
        $listRows = input('listRows', 10);
        $where    = ['user_id' => $this->auth->id, 'score' => ['neq', 0]];
        $total    = db('user_score_log')
            ->where($where)
            ->count();

        $page = new Page($total, $listRows);

        $list = db('user_score_log')
            ->field('id,type,score,memo,relation_id,createtime')
            ->where($where)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('createtime desc')
            ->select();

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];

        $this->success('請求成功', $data);
    }

/**
 * 用戶登錄
 *
 * @ApiMethod (POST)
 * @param string $account  賬號
 * @param string $password 密碼
 */
    public function login()
    {
        $account  = $this->request->post('account');
        $password = $this->request->post('password');
        if (! $account || ! $password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

/**
 * 手機驗證碼登錄
 *
 * @ApiMethod (POST)
 * @param string $mobile  手機號
 * @param string $captcha 驗證碼
 */
    public function mobilelogin()
    {
        $mobile  = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (! $mobile || ! $captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (! Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已經有賬號則直接登錄
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

/**
 * 註冊用戶
 *
 * @ApiMethod (POST)
 * @param string $username 用戶名
 * @param string $password 密碼
 * @param string $email    郵箱
 * @param string $mobile   手機號
 * @param string $code     驗證碼
 */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email    = $this->request->post('email');
        $mobile   = $this->request->post('mobile');
        $code     = $this->request->post('code');
        if (! $username || ! $password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && ! Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && ! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (! $ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

/**
 * 退出登錄
 * @ApiMethod (POST)
 */
    public function logout()
    {
        if (! $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

/**
 * 修改郵箱
 *
 * @ApiMethod (POST)
 * @param string $email   郵箱
 * @param string $captcha 驗證碼
 */
    public function changeemail()
    {
        $user    = $this->auth->getUser();
        $email   = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (! $email || ! $captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (! Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (! $result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification        = $user->verification;
        $verification->email = 1;
        $user->verification  = $verification;
        $user->email         = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

/**
 * 第三方登錄
 *
 * @ApiMethod (POST)
 * @param string $platform 平臺名稱
 * @param string $code     Code碼
 */
    public function third()
    {
        $url      = url('user/index');
        $platform = $this->request->post("platform");
        $code     = $this->request->post("code");
        $config   = get_addon_config('third');
        if (! $config || ! isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通過code換access_token和綁定用戶
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result,
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

/**
 * 重置密碼
 *
 * @ApiMethod (POST)
 * @param string $mobile      手機號
 * @param string $newpassword 新密碼
 * @param string $captcha     驗證碼
 */
    public function resetpwd()
    {
        $type        = $this->request->post("type");
        $mobile      = $this->request->post("mobile");
        $email       = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha     = $this->request->post("captcha");
        if (! $newpassword || ! $captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (! Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (! $user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (! $ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (! Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (! $user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (! $ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模擬一次登錄
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function imLogin()
    {
        $user = $this->auth->getUser();
        $im   = new ImSig();
        $user = $im->ext . $user->id;
        $res  = $im->account_check($user, false);
        if (! isset($res[$user])) {
            throw new \Exception('账号出错，请联系管理员');
        }

        if ($res[$user]['ResultCode'] == 0 && $res[$user]['AccountStatus'] == 'NotImported') {
            //创建客服账号
            $data = [
                'Identifier' => $user,
                'Nick'       => '客服',
            ];
            $res = $im->account_import($data, false);
            if (! isset($res['ActionStatus']) || $res['ActionStatus'] !== "OK" || ! isset($res['ErrorCode']) || $res['ErrorCode'] != 0) {
                throw new \Exception('生成客服账号失败');
            }

            sleep(2);
        } elseif ($res[$user]['ResultCode'] == 0 && $res[$user]['AccountStatus'] == 'Imported') {

        } else {
            throw new \Exception('客服账号不存，请联系管理员');
        }

        $sig = $im->genSig($user, 0, false);
        if ($sig) {
            $data = [
                'userId' => $user,
                'sign'   => $sig,
            ];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

/**
 * [setVisitingMaterials 登记来访资料]
 * @param string $value [description]
 */
    public function setVisitingMaterials($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('VisitingMaterials');
        if (! $validate->scene('do')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $time                     = time();
        $visiting_materials_model = new VisitingMaterials;
        $fields                   = $visiting_materials_model->getTableFields();
        $info                     = $visiting_materials_model->where(['user_id' => $this->auth->id])->find();
        $rq_data                  = $this->request->param();
        $data                     = [];
        foreach ($fields as $key => $value) {
            if ($value == 'id') {
                continue;
            }
            foreach ($rq_data as $k => $v) {
                if ($k == $value) {
                    $data[$k] = $v;
                }
            }
        }

        if (isset($data['id_card'])) {
            $id_card         = substr($data['id_card'], 0, -1);
            $data['id_card'] = $id_card . '(' . substr($data['id_card'], -1) . ')';
        }

        if (! $info) {
            $data['createtime'] = $time;
            $data['user_id']    = $this->auth->id;
            $status             = $visiting_materials_model->insert($data);
        } else {
            $info = $info->toArray();

            foreach ($info as $key => $value) {
                foreach ($data as $k => $v) {
                    if ($k == $key && $value && in_array($k, ['name', 'gender', 'birthday', 'id_card', 'return_permit'])) {
                        unset($data[$k]);
                    }
                }
            }
            if (! $data) {
                $this->error('未修改任何數據');
            }
            $data['updatetime'] = $time;
            $status             = $visiting_materials_model->where(['id' => $info['id']])->update($data);
        }

        if (! $status) {
            $this->error('操作失敗');
        }
        $this->success('操作成功');
    }

/**
 * [getVisitingMaterials 获取登记资料]
 * @param  string $value [description]
 * @return [type]        [description]
 */
    public function getVisitingMaterials($value = '')
    {
        $visiting_materials_model = new VisitingMaterials;
        $fields                   = $visiting_materials_model->getTableFields();
        $info                     = $visiting_materials_model->where(['user_id' => $this->auth->id])->find();
        if ($info) {
            $info = $info->toArray();
            unset($info['id']);
            unset($info['user_id']);
            unset($info['createtime']);
            unset($info['updatetime']);
        } else {
            $info = [];
            foreach ($fields as $key => $value) {
                if (in_array($value, ['id', 'user_id', 'createtime', 'updatetime'])) {
                    continue;
                }
                $info[$value] = '';
            }
        }

        if (isset($info['id_card'])) {
            $info['id_card'] = str_replace('(', '', $info['id_card']);
            $info['id_card'] = str_replace(')', '', $info['id_card']);
            $info['id_card'] = str_replace('（', '', $info['id_card']);
            $info['id_card'] = str_replace('）', '', $info['id_card']);
        }
        $info['region'] = Db::name('area')->where('id', $info['center_id'])->value('name');

        $this->success('請求成功', $info);
    }
}
